<template>
  <NuxtLoadingIndicator color="#fff577" />
  <div class="box" ref="box">
    <star></star>
    <div ref="myTabar" class="tabar  pt-3 flex flex-col items-center fixed top-0 w-full  bg-purple-900/30 z-20">
      <tabar @clickTabar="goTabar" :current=current></tabar>
      <div class="h-[1px] w-full bg-white mt-4  opacity-50 "></div>
    </div>
    <div class="big_box w-full  px-3 pt-3" :style="{ paddingTop: tabarTop.tabarTop }">
      <NuxtPage :page-key="route => route.fullPath" v-slot="{ Component }">
        <component :is="Component" ref="TypeRef" />
      </NuxtPage>
    </div>
  </div>
  <div class="mask" ref="mask">
    <h2 class="chose">RIVEN</h2>
  </div>
  <div v-if="isLoading" class="loading-overlay">
    <div class="loading">
      <svg viewBox="0 0 100 50" class="loading_icon">
        <path d="M50,25c0-12.14,9.84-21.99,21.99-21.99S93.98,12.86,93.98,25s-9.84,21.99-21.99,21.99S50,37.21,50,25.06
        S40.16,3.01,28.01,3.01S6.02,12.86,6.02,25s9.84,21.99,21.99,21.99S50,37.14,50,25c0-8.14,4.42-15.24,10.99-19.05
        C67.57,9.76,71.99,16.86,71.99,25c0,8.14-4.42,15.24-10.99,19.04c0,0,0,0,0,0c-3.23,1.87-6.99,2.94-10.99,2.94
        c-4.01,0-7.76-1.07-10.99-2.94h0C32.43,40.24,28.01,33.14,28.01,25c0-8.14,4.42-15.24,10.99-19.05l0,0
        C42.24,4.08,45.99,3.01,50,3.01s7.76,1.07,10.99,2.94l0,0" />
        <path d="M50,25c0-12.14,9.84-21.99,21.99-21.99S93.98,12.86,93.98,25s-9.84,21.99-21.99,21.99S50,37.21,50,25.06
        S40.16,3.01,28.01,3.01S6.02,12.86,6.02,25s9.84,21.99,21.99,21.99S50,37.14,50,25c0-8.14,4.42-15.24,10.99-19.05
        C67.57,9.76,71.99,16.86,71.99,25c0,8.14-4.42,15.24-10.99,19.04c0,0,0,0,0,0c-3.23,1.87-6.99,2.94-10.99,2.94
        c-4.01,0-7.76-1.07-10.99-2.94h0C32.43,40.24,28.01,33.14,28.01,25c0-8.14,4.42-15.24,10.99-19.05l0,0
        C42.24,4.08,45.99,3.01,50,3.01s7.76,1.07,10.99,2.94l0,0" />
      </svg>
      <div class="loading_circle"></div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { gsap } from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

const route = useRoute()
const TypeRef = ref()
const box = ref()
const myTabar = ref<HTMLElement | null>(null)
const tabarTop = useTabarTopStore()
const mask = ref()
let typeLock = false
let initialized = ref(false)
const current = ref(0)
const isLoading = ref(true)

// 添加初始化current值的函数
const initCurrentValue = () => {
  const path = route.path.slice(1) // 移除开头的斜杠
  if (path === '') {
    current.value = 0
  } else if (path === 'home') {
    current.value = 0
  } else if (path.startsWith('project')) {
    current.value = 1
  } else if (path.startsWith('blog')) {
    current.value = 2
  } else if (path.startsWith('about')) {
    current.value = 3
  }
}

useHead({
  title: 'My Blog',
  meta: [
    { name: 'description', content: 'My first site.' }
  ],
  bodyAttrs: {
    class: 'test'
  }
})

const goTabar = async (item: string, index: number) => {
  current.value = index
  if (item == 'home') {
    if (!typeLock && TypeRef.value?.change) {
      await new Promise(resolve => setTimeout(resolve, 1000))
      TypeRef.value.change(true)
      typeLock = true
    }
  }
  // if (item == 'blog') {
  //   box.value.style.backgroundImage = 'url(/bg2.jpg)'
  // } else {
  //   box.value.style.backgroundImage = 'url(/background.jpg)'
  // }
  let routePath = `/${item.toLowerCase()}`
  // if(item == 'blog')
  //   routePath = `/blog/hello`
  typeLock = false
  await navigateTo(routePath)
}

watch(
  () => route.path,
  async (newPath, oldPath) => {
    if (!initialized.value) {
      initialized.value = true
      return
    }
    await nextTick()
    // 更新current值
    initCurrentValue()
    if (TypeRef.value?.change) {
      goTabar("home", 0)
    }
  },
  { immediate: true }
)

// 加载动画控制
const loadingAnimation = {
  paths: ref<SVGPathElement[]>([]),
  circle: ref<HTMLElement | null>(null),
  animater: null as gsap.core.Timeline | null,

  init() {
    this.paths.value = [...document.querySelectorAll(".loading_icon path")] as SVGPathElement[]
    this.circle.value = document.querySelector(".loading_circle")

    let index = 0
    this.animater = gsap.timeline().fromTo(
      this.paths.value,
      {
        strokeDashoffset: (i) => {
          if (i === 0) return 0
          else return 480
        }
      },
      {
        strokeDashoffset: (i) => {
          if (i === 0) return -275
          else return 205
        },
        duration: 2,
        ease: "linear",
        onComplete: () => {
          index++
          if (index >= 1) this.finish()
          else this.animater?.restart()
        }
      }
    )
  },

  finish() {
    this.animater = gsap.timeline()
      .to(this.paths.value[1], {
        strokeWidth: 0,
        duration: 0.4,
        ease: "power3.out",
      })
      .to(this.paths.value[0], {
        strokeDasharray: '150 0 0 0 0 0 0 0 0 500',
        strokeDashoffset: -300,
        duration: 0.7,
        ease: "power3.out",
        onComplete: () => {
          const el = document.querySelector(".loading_icon")
          if (el?.parentNode) {
            el.parentNode.removeChild(el)
          }
        }
      }, "<")
      .to(this.circle.value, {
        opacity: 1,
        scale: 1.2,
        duration: 0.7,
        ease: "power3.out",
      }, "<0.3")
      .to(this.circle.value, {
        scale: 20,
        opacity: 0,
        duration: 1,
        ease: "power2.in",
        onComplete: () => {
          isLoading.value = false
        }
      })
  }
}

onMounted(async () => {
  await nextTick()
  tabarTop.setTabarTop(window.getComputedStyle(myTabar.value as HTMLElement).height)
  localStorage.setItem('tabarTop', tabarTop.tabarTop)
  // 在组件挂载时初始化current值
  initCurrentValue()
  // 初始化加载动画
  loadingAnimation.init()

  gsap.registerPlugin(ScrollTrigger)
  let tl = gsap.timeline({
    scrollTrigger: {
      trigger: ".box",
      scrub: 2,
      pin: true,
      start: "top top",
      end: "+=1000"
    },
    onComplete: () => {
      ScrollTrigger.getAll().forEach(trigger => trigger.disable(false))
      window.dispatchEvent(new Event("resize"))
        window.scrollTo({
          top: 0,
          behavior: 'smooth'
        })
      

      setTimeout(async () => {
        await nextTick()
        if (!typeLock && TypeRef.value?.change) {
          TypeRef.value.change(true)
          typeLock = true
        }
      }, 100)
    },
  })
  tl.to(".chose", { scale: 300, opacity: 0 })
    .from([".big_box", ".tabar"], {
      opacity: 0,
      y: -50,
      onReverseComplete: () => {
        if (TypeRef.value?.change) {
          TypeRef.value.change(false)
          typeLock = false
        }
      }
    })
})
</script>

<style scoped>
.box {
  min-height: 100vh;
  background-image: url('/background.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  background-attachment: fixed;
  transition: all 0.5s ease;
}

.tabar {
  backdrop-filter: blur(8px);
  z-index: 20;
}


.mask {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  left: 0;
  top: 0;
  pointer-events: none;
}

h2 {
  font-size: 100px;
  font-weight: 600;
  cursor: default;
  pointer-events: none;
  color: #fff;
}

/* 加载动画样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #b8a1e5;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading_icon {
  position: absolute;
  width: 35rem;
}

.loading_icon path {
  fill: none;
  stroke: #fff577;
  stroke-linecap: round;
}

.loading_icon path:nth-child(1) {
  stroke-width: 2;
  stroke-dasharray: 0 5 0 5 0 5 0 5 0 500;
}

.loading_icon path:nth-child(2) {
  stroke-width: 4;
  stroke-dasharray: 0 500 0 500;
  stroke-dashoffset: 480;
}

.loading_circle {
  position: absolute;
  width: 15rem;
  height: 15rem;
  border-radius: 100%;
  background-color: #fff577;
  opacity: 0;
  transform: scale(0);
}

.page-enter-active,
.page-leave-active {
  transition: opacity 0.5s ease;
}

.page-enter-from,
.page-leave-to {
  opacity: 0;
}
</style>